<script setup>
  import { ref, reactive } from 'vue'
  import { uniFetch } from '@/apis/uni-fetch.js'
  import { useUserStore } from '@/stores/users.js'
     // 表单元素的 ref 属性
  const accountForm = ref()

  // 表单数据
  const formData = reactive({
    account: '',
    password: '',
  })

  // 定义表单数据验证规则
  const accountRules = reactive({
    account: {
      rules: [
        { required: true, errorMessage: '请输入登录账号' },
        { pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' },
      ],
    },
  })

  // 监听表单的提交
  async function onFormSubmit() {
    try {
      // 验证通过
      const formData = await accountForm.value.validate()
      // 请求服务器登录接口获取服务器响应结果
      let res = await uniFetch.post('/driver/login/account', formData)
      console.log(res.data.data)
      const token = res.data.data
      const store = useUserStore()
      store.token = token
      // redirectTo不能跳转到tabBar配置的页面
      uni.switchTab({
        url:'/pages/task/index'
      })
      // 表单的数据
      console.log(formData)
    } catch (err) {
      // 验证失败
      console.log(err)
    }
  }
</script>

<template>
	<uni-forms class="login-form" ref="accountForm" :rules="accountRules"
    :model="formData">
		<uni-forms-item name="account">
			<input
				type="text"
				placeholder="请输入账号"
				class="uni-input-input"
				placeholder-style="color: #818181"
        v-model="formData.account"
			/>
		</uni-forms-item>
		<uni-forms-item name="password">
			<input
				type="text"
				placeholder="请输入密码"
				class="uni-input-input"
				placeholder-style="color: #818181"
        v-model="formData.password"
			/>
		</uni-forms-item>
		<button class="submit-button" @click="onFormSubmit()">登录</button>
	</uni-forms>
</template>


<style lang="scss" scoped>
	@import './styles.scss';
</style>
